package edu.utdallas.cs.securechat.main;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Properties;

import edu.utdallas.cs.securechat.ui.ClientFrame;
import edu.utdallas.cs.securechat.utils.Logger;

public class Main {
	public static void main(String[] args) {
		String serverDomainName = null;
		String masterPassword = "";
		Properties defaultProps = new Properties();
		String serverOrClient = "client";
		Logger.loggingLevel = Logger.INFO;

		for (int i = 0; i < args.length; i++) {
			String arg = args[i].trim().toLowerCase();
			if (arg.equals("server")) {
				try {
					serverDomainName = InetAddress.getLocalHost().getHostName();
					defaultProps.setProperty("server_domain_name", serverDomainName);
					defaultProps.store(new FileOutputStream("config.properties"), null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				serverOrClient = "server";
			} else if (arg.equals("client")) {
				try {
					defaultProps.load(new FileInputStream("config.properties"));
					serverDomainName = defaultProps.getProperty("server_domain_name");
					Logger.log(Logger.DEBUG, "Server Domain Name: " + serverDomainName);
				} catch (Exception e) {
					e.printStackTrace();
				}
				serverOrClient = "client";
			} else if (arg.equals("-d")) {
				Logger.loggingLevel = Logger.DEBUG;
			} else if (arg.equals("-m")){
				masterPassword = args[i+1];
				i++;
			} else {
				Logger.log(Logger.ERROR, "Argument not supported! Use server or client.");
			}
		}
		
		if(serverOrClient.equals("server")){
			Server server = new Server(masterPassword);
			try {
				server.startServer();
			} catch (Exception e) {
				System.err.println(e);
			}
		}else{
			try {
				defaultProps.load(new FileInputStream("config.properties"));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			serverDomainName = defaultProps.getProperty("server_domain_name");
			ClientFrame client = new ClientFrame(serverDomainName);
			client.startClient();
		}

	}
}
